<template>
  <div class="add-push-item">
    <ul class="pics">
      <li v-for="(picItem, picIndex) in item.pics" :key="picIndex" @click.capture="onClick(picIndex)">
        <div v-if="picItem.loading" v-loading="picItem.loading" class="loading-con"></div>
        <img v-else :src="picItem.pic_url">
        <el-upload
          :action="fileUploadS3Url"
          multiple
          name="pic"
          :with-credentials="true"
          :data="{siteid: site_id, pic_index: picIndex}"
          :limit="limitUploadNum"
          :show-file-list="false"
          :on-success="onUpdateWbPic"
          :before-upload="onUpdataBeforeUpload"
          >
          <p>更换图片</p>
        </el-upload>
        <el-icon class="btn-delete" @click.stop.prevent="onDeleteWbImgItem(picIndex)"><circle-close-filled /></el-icon>
      </li>
      <li v-if="item.pics.length < 9">
        <el-upload
          :action="fileUploadS3Url"
          multiple
          name="pic"
          :with-credentials="true"
          :data="{siteid: site_id}"
          :limit="limitUploadNum"
          :show-file-list="false"
          :on-success="onAddWbPic"
          :before-upload="onAddUpdateBeforeUpload"
          >
          <el-icon><plus /></el-icon>添加图片
        </el-upload>
      </li>
    </ul>
  </div>
</template>


<script setup lang="ts">
import { isHasOwnProperty, randomUploadFileName } from '@/utils/'
import { useWebSiteStore } from '@/store/web/site'
import { useWebControlsStore } from '@/store/web/controls'
import { ElMessage } from 'element-plus'
import { ElNotification } from 'element-plus'
import { fileUploadS3Url } from '@/service/web/api'

interface Props {
  item: IPushItem,
  index: number,
  controlId: string,
}
const props = withDefaults(defineProps<Props>(), {
  index: -1,
  controlId: '',
})
const item = props.item
const index = props.index
const controlId = props.controlId

const useWebSite = useWebSiteStore()
const useWebControls = useWebControlsStore()
const site_id = computed(() => {
  return useWebSite.id
})
const limitUploadNum = 9
const size = 1024 * 1024 * 1
let currentItemIndex = -1

const onClick = (picIndex: number) => {
  currentItemIndex = picIndex
  if(!item.pics[picIndex].pic_id) {
    onDeleteWbImgItem(picIndex)
  }
}
const onAddUpdateBeforeUpload = (file: any) => {
  beforeUpload(file, true)
}
const onUpdataBeforeUpload = (file: any) => {
  beforeUpload(file, false)
}
const beforeUpload = (file: any, isAdd: boolean) => {
  let suffix = file.name.split(".")[1]
  file.filename = randomUploadFileName(Number(useWebSite.id)) + "." + suffix
  let isJPG: boolean = false
  if(file.type === 'image/png' || file.type === 'image/gif' || file.type === 'image/jpeg') {
    isJPG = true
  }
  const isLt2M = file.size / 1024 / 1024 < 1;

  if (!isJPG) {
    showMessage('上传文件格式不对!')
    return false
  }
  if (!isLt2M) {
    showMessage(`上传文件大小不能超过 ${size/1024/1024}M !`)
    return false

  }
  if(isJPG && isLt2M) {
    if(isAdd) {
      item.pics.push({ loading: true, pic_id:'', pic_url: ''})
    } else {
      item.pics[currentItemIndex]['loading'] = true
    }
  }
  return isJPG && isLt2M;
}
const onDeleteWbImgItem = (picIndex: number) => {
  item.pics.splice(picIndex, 1)
  const params = {item: item, index: index, controlId: controlId}
  useWebControls.updateWbComponentItem(params)
}
const onUpdateWbImgItem = () => {
  const params = {item:item, index: index, controlId: controlId}
  useWebControls.updateWbComponentItem(params);
}
const onUpdateWbPic = (response: any) => {
  if(response.code > 0) {
    ElNotification({
      title: '',
      message: response.msg,
      type: 'success',
      showClose: false,
    })
    onDeleteWbImgItem(currentItemIndex >= 0 ? currentItemIndex : item.pics.length-1)
  } else {
    const data = response.data
    item.pics[data.pic_index].loading = false
    item.pics[data.pic_index].pic_id = data.pic_id
    item.pics[data.pic_index].pic_url = data.original_pic
    const params = {item:item, index: index, controlId: controlId}
    useWebControls.updateWbComponentItem(params);
  }
}
const onAddWbPic = (response: any) => {
  if(response.code > 0){
    ElNotification({
      title: '',
      message: response.msg,
      type: 'success',
      showClose: false
    });
    onDeleteWbImgItem(currentItemIndex >= 0 ? currentItemIndex : item.pics.length-1)
  } else {
    const data = response.data;
    const len = item.pics.length;
    for(let i = 0; i < len;  i++) {
      const pic = item.pics[i]
      if(isHasOwnProperty(pic, 'loading') && pic.loading) {
        pic.loading = false
        pic.pic_id = data.pic_id
        pic.pic_url = data.original_pic
        pic.original = data.original_pic
        pic.thumbnail = data.thumbnail_pic
        break
      }
    }
    const params = {item: item, index:index, controlId: controlId}
    useWebControls.updateWbComponentItem(params)
  }
}
const showMessage = (msg: string) => {
  ElMessage({ message: msg, type: 'error' })
}
</script>
